package com.le.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

// 验证码的功能
public class response02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //让浏览器五秒刷新一次
       resp.setHeader("refresh","3");

        //在内存中创建一个图片
        BufferedImage bufferedImage=new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //得到图片 并且得到一个笔去在画面上写东西
        Graphics2D graphics=(Graphics2D)bufferedImage.getGraphics();
        //设置背景颜色
        graphics.setColor(Color.black);
        graphics.fillRect(0,0,80,20); //ti==填充
        //给图片写数据
        graphics.setColor(Color.white);
        graphics.setFont(new Font(null,Font.BOLD,10));
        graphics.drawString(makeNum(),0,10);

        //告诉浏览器 ，这个请求用图片的形式打开
       resp.setContentType("image/jpeg");


        //把图片写给浏览器
        ImageIO.write(bufferedImage,"jpg",resp.getOutputStream());


    }
    public String makeNum(){
        Random random=new Random();
       String num= random.nextInt(9999)+"";

       StringBuffer sb=new StringBuffer();
       //保证验证码是四位数字
        for (int i = 0; i <4-num.length() ; i++) {
            sb.append("0");
        }
        String s=sb.toString()+num;
        return s;
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
